package com.manage.server.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.manage.context.BaseContext;
import com.manage.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtUserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        JwtUtils jwtUtils = new JwtUtils();
        String  token = request.getHeader("token");
        if(token==null|| jwtUtils.isTokenExpired(token)){
            return false;
        }
        try {
            BaseContext.setUserId(jwtUtils.getUserIdFromToken(token));
            return true;
        } catch (JWTVerificationException e) {
            response.setStatus(401);
            return false;
        }

    }
}
